//
//  SortClassVC.m
//  dyseller
//
//  Created by 红喇叭 on 2017/11/21.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "SortClassVC.h"
#import "XRDragTableView.h"
#import "SortClassCell.h"

@interface SortClassVC ()<UITableViewDataSource,UITableViewDelegate>{
    NSMutableArray *_primitiveArray;//保存原始数据
}

@property(nonatomic,strong)XRDragTableView *sortClassTableView;

@end

@implementation SortClassVC

- (void)viewDidLoad {
    [super viewDidLoad];
     [self setNavTitle:@"分类排序" titleColor:[UIColor blackColor] font:font17];
    [self.view addSubview:self.sortClassTableView];
    self.sortClassTableView.dataArray = _dataSort;
    _primitiveArray = [NSMutableArray arrayWithArray:_dataSort];
    UIButton *savebtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [savebtn setTitle:@"保存" forState:0];
    [savebtn setTitleColor:kBlackColor forState:0];
    [savebtn addTarget:self action:@selector(saveFoodClassSort) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:savebtn];
    
    __weak typeof (self)weakself = self;
    [self.backBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        if([self dataContrast]){
           [weakself.navigationController popViewControllerAnimated:YES];
        }else{
            [weakself backAction];
        }
    }];
}

- (void)backAction{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否保存修改的信息" preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof (self)weakSelf = self;
    [alertController addAction:[UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf saveFoodClassSort];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (BOOL)dataContrast{
    NSString *str = [_primitiveArray componentsJoinedByString:@","];
    NSString *str1 = [ToolClass md5:str];
    NSString *ptr = [_dataSort componentsJoinedByString:@","];
    NSString *ptr1 = [ToolClass md5:ptr];
    return [str1 isEqualToString:ptr1];
}

#pragma  mark =======网络请求========
- (void)saveFoodClassSort{
    
    if([self dataContrast]){
        [AlertUtils showToastWithMessage:@"您没有进行操作，不需要保存！" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        return;
    }
    NSMutableArray *newSort = @[].mutableCopy;
    for(int i=0;i<_dataSort.count;i++){
        CategoryListModel *model = _dataSort[i];
        NSData *data = [model yy_modelToJSONData];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSMutableDictionary *newdic = dic.mutableCopy;
        newdic[@"sort"] = [NSString stringWithFormat:@"%ld",_dataSort.count-i];
        [newSort addObject:newdic];
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:newSort options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

     __weak typeof (self)weakSelf = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/GoodsCate/categorySort" isactive:YES parameter:@{@"data":jsonStr} successBlock:^(PPHttpRequest *request,id responseObj) {
        
        [AlertUtils showToastWithMessage:@"保存成功" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        
       // _primitiveArray = [NSMutableArray arrayWithArray:_dataSort];
        [weakSelf.navigationController popViewControllerAnimated:YES];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        
    }];

    
}

- (void)deleteFoodClass:(UIButton *)sender{
    CategoryListModel *model = _dataSort[sender.tag];
    __weak typeof (self)weakSelf = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/GoodsCate/categoryDel" isactive:YES parameter:@{@"category_id":model.categoryID} successBlock:^(PPHttpRequest *request, NSArray* responseObj) {
        
        [AlertUtils showToastWithMessage:@"删除成功" inView:nil hideAfterDelay:2.0 beIndeter:NO];
        [weakSelf.dataSort removeObject:model];
        [weakSelf.sortClassTableView reloadData];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        
    }];
    
}

#pragma  mark ========懒加载========
- (XRDragTableView *)sortClassTableView{
    if(_sortClassTableView == nil){
        _sortClassTableView = [[XRDragTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-NavigationHeight-TableSafe) style:UITableViewStylePlain];
        _sortClassTableView.delegate = self;
        _sortClassTableView.dataSource = self;
        _sortClassTableView.scrollSpeed = 10;
        _sortClassTableView.estimatedRowHeight = 0;
        _sortClassTableView.estimatedSectionHeaderHeight = 0;
        _sortClassTableView.estimatedSectionFooterHeight = 0;
        [_sortClassTableView registerClass:[SortClassCell class] forCellReuseIdentifier:@"SortClassCell"];
    }
    return _sortClassTableView;
}


//置顶的数据源处理方法
- (void)stickAction:(UIButton *)sender{
    
    CategoryListModel *model = _dataSort[sender.tag];
    [_dataSort removeObject:model];
    [_dataSort insertObject:model atIndex:0];
    [self.sortClassTableView reloadData];
}


#pragma  mark ========UITableView 的代理方法========
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataSort.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SortClassCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SortClassCell" forIndexPath:indexPath];
    if(indexPath.row==0) {
        cell.stickBtn.hidden = YES;
    }else{
        cell.stickBtn.hidden = NO;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.datamModel = _dataSort[indexPath.row];
    
    [cell.dragBtn setBackgroundImage:[UIImage new] forState:UIControlStateNormal];
    [cell.dragBtn  addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self.sortClassTableView action:@selector(moveRow:)]];
    
    cell.stickBtn.tag = indexPath.row;
    [cell.stickBtn addTarget:self action:@selector(stickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.deleteClassBtn.tag = indexPath.row;
    [cell.deleteClassBtn addTarget:self action:@selector(deleteFoodClass:) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 64;
}

@end
